'''
@Description: In User Settings Edit
@Author: your name
@Date: 2019-08-13 17:14:46
@LastEditTime: 2019-12-12 10:11:18
@LastEditors: Please set LastEditors
'''
from server.pao_python.pao.service.data.mongo_db import MongoService, MongoFilter, C, N, F, as_date
from ...service.buss_pub.bill_manage import BillManageService, OperationType, TypeId, Status
from ...service.common import insert_data, find_data, update_data, delete_data, get_condition, get_info, get_current_user_id, GetInformationByIdCard, ImageSize, operation_result, ResultData, insert_many_data
from ...pao_python.pao.service.security.security_utility import get_current_account_id
from ...pao_python.pao.service.security.security_service import RoleService
import hashlib
import re
import datetime
import uuid
import base64
import pandas as pd
from enum import Enum
from ...pao_python.pao.data import process_db, dataframe_to_list, DataProcess, DataList, get_cur_time
from ...service.mongo_bill_service import MongoBillFilter
from ...service.constant import SubsidyRecordState, SubsidyRecordSubsidyType
import requests
import json
from ...pao_python.pao.remote import JsonRpc2Error
import os
import shutil
from ...service.buss_pub.message_manage import MessageManageService
# -*- coding: utf-8 -*-

'''
补贴管理函数
'''


class AllowanceManageService(MongoService):
    ''' 补贴管理 '''
    Allowance = 'PT_Allowance_Manage'

    def __init__(self, db_addr, db_port, db_name, db_user, db_pwd, inital_password, session):
        self.db_addr = db_addr
        self.db_port = db_port
        self.db_name = db_name
        self.db_user = db_user
        self.db_pwd = db_pwd
        self.inital_password = inital_password
        if session:
            self.session = session
        else:
            self.session = {
                "user_id": '23b3630a-d92c-11e9-8b9a-983b8f0bcd67',
                'organization_id': '7e7e2fec-d91d-11e9-8e1d-983b8f0bcd67'
            }
        self.bill_manage_server = BillManageService(
            self.db_addr, self.db_port, self.db_name, self.db_user, self.db_pwd, self.inital_password, self.session)
        self.MessageManageService = MessageManageService(
            self.db_addr, self.db_port, self.db_name, self.db_user, self.db_pwd, self.inital_password, self.session)

    def get_allowance_list(self, org_list, condition, page=None, count=None):
        '''查询申请列表'''
        keys = ['id', 'name', 'status', 'create_date', 'allowance_type']
        values = self.get_value(condition, keys)
        start = N()
        end = N()
        if(bool(1-isinstance(values['create_date'], N))):
            start = values['create_date']+"T00:00:00.00Z"
            end = values['create_date']+"T23:59:59.00Z"
        _filter = MongoBillFilter()
        _filter.match_bill((C('id') == values['id'])
                           & (C('name').like(values['name']))
                           & (C('allowance_type').like(values['allowance_type']))
                           & (C('status') == values['status'])
                           & (C('create_date') > as_date(start))
                           & (C('create_date') < as_date(end))
                           & (C('organization_id').inner(org_list)))\
            .project({'_id': 0})
        res = self.page_query(_filter, self.Allowance, page, count)
        return res

    def get_currentUser_allowance_list(self, condition, page=None, count=None):
        '''查询当前用户的申请信息'''
        keys = ['apply_user_id', 'allowance_type']
        begin_date = datetime.datetime(
            datetime.datetime.now().year, 6, 15, 0, 0, 0)
        end_date = datetime.datetime(datetime.datetime.now(
        ).year+1, 6, 1, 23, 59, 59)-datetime.timedelta(days=1)
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('apply_user_id') == values['apply_user_id'])
                           & (C('allowance_type').like(values['allowance_type']))
                           & (C('create_date') > begin_date)
                           & (C('create_date') < end_date)
                           )\
            .project({'_id': 0})
        res = self.page_query(_filter, self.Allowance, page, count)
        print("数据》》》》》》》》》》》》》》》》》", res)
        return res

    def get_allowance_applied_list(self, org_list, condition, page=None, count=None):
        '''查询待审批列表'''
        keys = ['id', 'name', 'status', 'create_date', 'allowance_type']
        condition['status'] = ['已申请', '审批中']
        values = self.get_value(condition, keys)
        persion_id = get_current_user_id(self.session)
        _filter = MongoBillFilter()
        _filter.lookup_bill('PT_Approval_Process', 'id', 'business_id', 'process')\
            .add_fields({'new_field': self.ao.array_filter(
                "$process", "aa", ((F('$aa.approval_user_id') == persion_id) & (F('$aa.step_no') == (F('step_no'))) & (F('$aa.status') == '待审批')).f)}).match((C("new_field") != None) & (C("new_field") != []))\
            .match_bill((C('id') == values['id'])
                        & (C('name').like(values['name']))
                        & (C('allowance_type').like(values['allowance_type']))
                        & (C('status').inner(values['status']))
                        & (C('create_date').like(values['create_date'])))\
            .project({'_id': 0, 'new_field._id': 0, 'process._id': 0})
        res = self.page_query(_filter, self.Allowance, page, count)
        return res

    def update_allowance(self, allowance):
        '''# 新增/修改申请'''
        res = 'Fail'
        if 'id' in allowance.keys():
            # 判断是否已经有过程表数据，目前保存并提交的逻辑只有在被打回时候才执行
            _filter = MongoBillFilter()
            _filter.match_bill((C('business_id') == allowance['id'])
                               & (C('step_no') == allowance['step_no']))\
                .project({'_id': 0})
            res_Process = self.query(_filter, 'PT_Approval_Process')
            if len(res_Process) > 0:
                # 如果存在，则把过程数据的status改回待审批
                process_data = res_Process[0]
                process_data['status'] = '待审批'
                allowance['status'] = '审批中'
                data = [allowance, process_data]
                bill_id = self.bill_manage_server.add_bill(
                    OperationType.update.value, TypeId.allowance.value, data, [self.Allowance, 'PT_Approval_Process'])
                if bill_id:
                    res = 'Success'
        else:
            print(1111111111111111111111111111111111111111)
            _filter = MongoBillFilter()
            _filter.match_bill((C('name') == allowance['name'])
                               & (C('id_card') == allowance['id_card']))\
                .project({'_id': 0})
            user_res = self.query(_filter, 'PT_User')
            print(1111111111111111111111111111111111111111, user_res)
            if len(user_res) > 0:
                # 判断当前用户是否已经有过类型相同的申请
                _filter = MongoBillFilter()
                _filter.match_bill((C('apply_user_id') == user_res[0]['id'])
                                   & (C('allowance_type').like(allowance['allowance_type'][0:4]))
                                   & (C('step_no') != -1))\
                    .project({'_id': 0})
                apply_list = self.query(_filter, 'PT_Allowance_Manage')
                print("人员信息>>>>>>>>>>>>>", apply_list)
                if len(apply_list) > 0:
                    res = '同一个人每次只能申请一次同类型的补贴'
                    return res
                else:
                    allowance['apply_user_id'] = user_res[0]['id']
                    allowance['status'] = "已申请"
                    data_info = get_info(allowance, self.session)
                    # 根据审批定义新增审核过程表数据，新增业务表数据
                    _filter = MongoBillFilter()
                    _filter.match_bill((C('approval_type') == 'subsidy'))\
                        .project({'_id': 0})
                    res_define = self.query(_filter, 'PT_Approval_Define')
                    print(res_define,
                          user_res[0]['personnel_info']['personnel_category'])
                    if len(res_define) > 0 and len(res_define[0]['approval_list']) > 0:
                        for defineList in res_define:
                            print('hahahahahaha')
                            print(defineList['type'] == "长者" and user_res[0]
                                  ['personnel_info']['personnel_category'] == '长者')
                            # 工作人员
                            if defineList['type'] == "工作人员" and user_res[0]['personnel_info']['personnel_category'] == '工作人员':
                                print("到这了吗？？？", 111111111111)
                                for approval in defineList['approval_list']:
                                    # OrganizationID = ""
                                    if approval['step_no'] == 1:
                                        print(
                                            "到这了吗？？？", user_res[0]['organization_id'])
                                        process_data_list = []
                                        # 根据用户的id找出所属机构id(所属服务商)
                                        aboutOrganizationID = user_res[0]['organization_id']
                                        print("到这了吗？？？", aboutOrganizationID)
                                        # 根据服务商id找到所属行政区划
                                        _filter = MongoBillFilter()
                                        _filter.match_bill((C('id') == aboutOrganizationID))\
                                            .project({'_id': 0})
                                        aboutOrganizationInfo = self.query(
                                            _filter, 'PT_User')
                                        area_id = aboutOrganizationInfo[0]['admin_area_id']
                                        # 根据行政区划id找到当前区划下的所有组织机构,并从所有机构中找出民政局机构
                                        _filter = MongoBillFilter()
                                        _filter.match_bill((C('admin_area_id') == area_id) & (C('personnel_type') == '2') & (C('organization_info.personnel_category') == '民政'))\
                                            .project({'_id': 0})
                                        AreaOrganizationInfo = self.query(
                                            _filter, 'PT_User')
                                        mzOrganizationId = AreaOrganizationInfo[0]['id']
                                        # 根据角色id以及机构id确认所对应的用户id
                                        _filter = MongoBillFilter()
                                        _filter.match_bill((C('role_id') == approval['approval_user_id']) & (C('role_of_account_id') == mzOrganizationId))\
                                            .project({'_id': 0})
                                        aboutUserIdList = self.query(
                                            _filter, 'PT_Set_Role')
                                        approval_user_id = aboutUserIdList[0]['principal_account_id']
                                        process_data = {"define_id": res_define[0]['id'], "business_id": data_info['id'], "approval_user_id":
                                                        approval_user_id, "step_no": approval['step_no'], "opinion": [], "status": "待审批"}
                                        process_data_list.append(
                                            get_info(process_data, self.session))
                                        data_info['step_no'] = process_data_list[0]['step_no']
                                        data = [data_info, process_data_list]
                                        bill_id = self.bill_manage_server.add_bill(
                                            OperationType.add.value, TypeId.allowance.value, data, [self.Allowance, 'PT_Approval_Process'])
                                        if bill_id:
                                            res = 'Success'
                                    if approval['step_no'] == 2:
                                        process_data_list = []
                                        # 查找属于平台的组织结构
                                        _filter = MongoBillFilter()
                                        _filter.match_bill((C('personnel_type') == '2') & (C('organization_info.personnel_category') == '平台'))\
                                            .project({'_id': 0})
                                        forumInfo = self.query(
                                            _filter, 'PT_User')
                                        print(forumInfo)
                                        # 拿到平台的id以及角色id确定可以审核的人id
                                        _filter = MongoBillFilter()
                                        _filter.match_bill((C('role_id') == approval['approval_user_id']) & (C('role_of_account_id') == forumInfo[0]['id']))\
                                            .project({'_id': 0})
                                        aboutUserIdList = self.query(
                                            _filter, 'PT_Set_Role')
                                        approval_user_id = aboutUserIdList[0]['principal_account_id']
                                        process_data = {"define_id": res_define[0]['id'], "business_id": data_info['id'], "approval_user_id":
                                                        approval_user_id, "step_no": approval['step_no'], "opinion": [], "status": "待审批"}
                                        process_data_list.append(
                                            get_info(process_data, self.session))
                                        data = [process_data_list]
                                        bill_id = self.bill_manage_server.add_bill(
                                            OperationType.add.value, TypeId.allowance.value, data, ['PT_Approval_Process'])
                                        if bill_id:
                                            res = 'Success'
                                    # 找到上级行政区划的机构id
                                    if approval['step_no'] == 3:
                                        print(333333)
                                        process_data_list = []
                                        # 根据用户的id找出所属机构id
                                        towmOrganizationID = user_res[0]['organization_id']
                                   #     先查找当前机构的行政区划
                                        _filter = MongoBillFilter()
                                        _filter.match_bill((C('id') == towmOrganizationID))\
                                            .project({'_id': 0})
                                        aboutOrganizationInfo = self.query(
                                            _filter, 'PT_User')
                                        area_id = aboutOrganizationInfo[0]['admin_area_id']
                                        # 根据当前行政区划id查找上一级区划id
                                        _filter = MongoBillFilter()
                                        _filter.match_bill((C('id') == area_id))\
                                            .project({'_id': 0})
                                        areaInfo = self.query(
                                            _filter, 'PT_Administration_Division')
                                        parentId = areaInfo[0]['parent_id']
                                        # 根据上级区划id查找当前区域下的所有组织机构,并从所有机构中找出民政局机构
                                        _filter = MongoBillFilter()
                                        _filter.match_bill((C('admin_area_id') == parentId) & (C('personnel_type') == '2') & (C('organization_info.personnel_category') == '民政'))\
                                            .project({'_id': 0})
                                        upAreaOrganizationId = self.query(
                                            _filter, 'PT_User')
                                        print(4444444444444444)
                                        # OrganizationID = upAreaOrganizationInfo['']
                                        # 根据角色id以及机构id确认所对应的用户id
                                        _filter = MongoBillFilter()
                                        _filter.match_bill((C('role_id') == approval['approval_user_id']) & (C('role_of_account_id') == upAreaOrganizationId[0]['id']))\
                                            .project({'_id': 0})
                                        aboutUserIdList = self.query(
                                            _filter, 'PT_Set_Role')
                                        print(5555555555, aboutUserIdList)
                                        approval_user_id = aboutUserIdList[0]['principal_account_id']
                                        process_data = {"define_id": res_define[0]['id'], "business_id": data_info['id'], "approval_user_id":
                                                        approval_user_id, "step_no": approval['step_no'], "opinion": [], "status": "待审批"}
                                        process_data_list.append(
                                            get_info(process_data, self.session))
                                        data = [process_data_list]
                                        bill_id = self.bill_manage_server.add_bill(
                                            OperationType.add.value, TypeId.allowance.value, data, ['PT_Approval_Process'])
                                        if bill_id:
                                            res = 'Success'
                            if defineList['type'] == "长者" and user_res[0]['personnel_info']['personnel_category'] == '长者':
                                print(11111111111)
                                for approval in defineList['approval_list']:
                                    if approval['step_no'] == 1:
                                        process_data_list = []
                                        # 根据长者的信息去user表查所属行政区划id
                                        _filter = MongoBillFilter()
                                        _filter.match_bill((C('id') == user_res[0]['id']))\
                                            .project({'_id': 0})
                                        elderInfo = self.query(
                                            _filter, 'PT_User')
                                        print(
                                            "长者11111111111111111111111111111111111111111111", elderInfo)
                                        # 根据行政区划id找出当前区划下的民政机构
                                        _filter = MongoBillFilter()
                                        _filter.match_bill((C('admin_area_id') == elderInfo[0]['admin_area_id']) & (C('personnel_type') == '2') & (C('organization_info.personnel_category') == '民政'))\
                                            .project({'_id': 0})
                                        mzOrganizationInfo = self.query(
                                            _filter, 'PT_User')
                                        print(
                                            "长者2222222222222222222222222222222222", mzOrganizationInfo)
                                        if len(mzOrganizationInfo) > 0:
                                            # 根据角色id以及机构id找出审核人id
                                            _filter = MongoBillFilter()
                                            _filter.match_bill((C('role_id') == approval['approval_user_id']) & (C('role_of_account_id') == mzOrganizationInfo[0]['id']))\
                                                .project({'_id': 0})
                                            aboutUserIdList = self.query(
                                                _filter, 'PT_Set_Role')
                                            approval_user_id = aboutUserIdList[0]['principal_account_id']
                                            print(
                                                "长者33333333333333333333333333333333333333333333", approval_user_id)
                                            process_data = {"define_id": res_define[0]['id'], "business_id": data_info['id'], "approval_user_id":
                                                            approval_user_id, "step_no": approval['step_no'], "opinion": [], "status": "待审批"}
                                            process_data_list.append(
                                                get_info(process_data, self.session))
                                            data_info['step_no'] = process_data_list[0]['step_no']
                                            data = [data_info, process_data_list]
                                            bill_id = self.bill_manage_server.add_bill(
                                                OperationType.add.value, TypeId.allowance.value, data, [self.Allowance, 'PT_Approval_Process'])
                                            if bill_id:
                                                res = 'Success'
                                        else:
                                            res = '申请失败，该长者所属的区域没有相关民政信息，请联系管理员'
                                    if approval['step_no'] == 2:
                                        process_data_list = []
                                        # 根据长者的信息去user表查所属行政区划id
                                        _filter = MongoBillFilter()
                                        _filter.match_bill((C('id') == user_res[0]['id']))\
                                            .project({'_id': 0})
                                        elderInfo = self.query(
                                            _filter, 'PT_User')
                                        print(
                                            "长者444444444444444444444444444444444444", elderInfo)
                                        # 根据当前行政区划id查找上一级区划id
                                        _filter = MongoBillFilter()
                                        _filter.match_bill((C('id') == elderInfo[0]['admin_area_id']))\
                                            .project({'_id': 0})
                                        upAreaInfo = self.query(
                                            _filter, 'PT_Administration_Division')
                                        parentId = upAreaInfo[0]['parent_id']
                                        print(
                                            "父级行政区划id>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", parentId)
                                        # 根据上一级行政区划id找出区划下的民政机构
                                        _filter = MongoBillFilter()
                                        _filter.match_bill((C('admin_area_id') == parentId) & (C('personnel_type') == '2') & (C('organization_info.personnel_category') == '民政'))\
                                            .project({'_id': 0})
                                        upAreaOrganizationInfo = self.query(
                                            _filter, 'PT_User')
                                        print(
                                            "长者55555555555555555555555555555555", upAreaOrganizationInfo)
                                        if len(upAreaOrganizationInfo) > 0:
                                            # 根据角色id和机构id确定审核人id
                                            _filter = MongoBillFilter()
                                            _filter.match_bill((C('role_id') == approval['approval_user_id']) & (C('role_of_account_id') == upAreaOrganizationInfo[0]['id']))\
                                                .project({'_id': 0})
                                            aboutUserIdList = self.query(
                                                _filter, 'PT_Set_Role')
                                            approval_user_id = aboutUserIdList[0]['principal_account_id']
                                            print(
                                                "长者666666666666666666666666666", approval_user_id)
                                            process_data = {"define_id": res_define[0]['id'], "business_id": data_info['id'], "approval_user_id":
                                                            approval_user_id, "step_no": approval['step_no'], "opinion": [], "status": "待审批"}
                                            process_data_list.append(
                                                get_info(process_data, self.session))
                                            data = [process_data_list]
                                            bill_id = self.bill_manage_server.add_bill(
                                                OperationType.add.value, TypeId.allowance.value, data, ['PT_Approval_Process'])
                                            if bill_id:
                                                res = 'Success'
                                        else:
                                            res = '申请失败，该长者所属的区域没有相关民政信息，请联系管理员'
                                    if approval['step_no'] == 3:
                                        process_data_list = []
                                        # 根据长者的信息去user表查所属行政区划id
                                        _filter = MongoBillFilter()
                                        _filter.match_bill((C('id') == user_res[0]['id']))\
                                            .project({'_id': 0})
                                        elderInfo = self.query(
                                            _filter, 'PT_User')
                                        print(
                                            "长者77777777777777777777777777777777777777", elderInfo)
                                        # 根据当前行政区划id查找上一级区划id
                                        _filter = MongoBillFilter()
                                        _filter.match_bill((C('id') == elderInfo[0]['admin_area_id']))\
                                            .project({'_id': 0})
                                        upAreaInfo = self.query(
                                            _filter, 'PT_Administration_Division')
                                        parentId = upAreaInfo[0]['parent_id']
                                        # 根据上一级行政区划id去找再上一级的行政区划id
                                        _filter = MongoBillFilter()
                                        _filter.match_bill((C('id') == parentId))\
                                            .project({'_id': 0})
                                        upParentAreaInfo = self.query(
                                            _filter, 'PT_Administration_Division')
                                        upParentId = upParentAreaInfo[0]['parent_id']
                                        # 根据上一级行政区划id找出区划下的民政机构
                                        _filter = MongoBillFilter()
                                        _filter.match_bill((C('admin_area_id') == upParentId) & (C('personnel_type') == '2') & (C('organization_info.personnel_category') == '民政'))\
                                            .project({'_id': 0})
                                        upAreaOrganizationInfo = self.query(
                                            _filter, 'PT_User')
                                        print(
                                            "长者8888888888888888888888888888888888888888888888", upAreaOrganizationInfo)
                                        if len(upAreaOrganizationInfo) > 0:
                                            # 根据角色id和机构id确定审核人id
                                            _filter = MongoBillFilter()
                                            _filter.match_bill((C('role_id') == approval['approval_user_id']) & (C('role_of_account_id') == upAreaOrganizationInfo[0]['id']))\
                                                .project({'_id': 0})
                                            aboutUserIdList = self.query(
                                                _filter, 'PT_Set_Role')
                                            approval_user_id = aboutUserIdList[0]['principal_account_id']
                                            print(
                                                "长者99999999999999999999999999999999999999", approval_user_id)
                                            process_data = {"define_id": res_define[0]['id'], "business_id": data_info['id'], "approval_user_id":
                                                            approval_user_id, "step_no": approval['step_no'], "opinion": [], "status": "待审批"}
                                            process_data_list.append(
                                                get_info(process_data, self.session))
                                            print("数据/？？？？？？？？？",
                                                  process_data_list)
                                            data = [process_data_list]
                                            bill_id = self.bill_manage_server.add_bill(
                                                OperationType.add.value, TypeId.allowance.value, data, ['PT_Approval_Process'])
                                            if bill_id:
                                                res = 'Success'
                                        else:
                                            res = '申请失败，该长者所属的区域没有相关民政信息，请联系管理员'
            else:
                res = '申请失败，系统中没有该长者信息'
        return res

    def del_allowance(self, ids):
        ''' 删除申请 '''
        res = 'Fail'
        for i in ids:
            bill_id = self.bill_manage_server.add_bill(
                OperationType.delete.value, TypeId.allowance.value, {'id': i}, self.Allowance)
        if bill_id:
            res = 'Success'
        return res

    def get_assessment_template(self, org_list):
        '''获取评估模板'''
        _filter = MongoFilter()
        _filter.match((C('bill_status') == 'valid') & (
            C('organization_id').inner(org_list))).project({'_id': 0})
        res = self.page_query(_filter, "PT_Assessment_Template", 1, 999)
        return res

    def add_allowance_define(self, allowance_define):
        '''新增或修改模板定义'''
        res = 'Fail'
        if 'id' in allowance_define.keys():
            bill_id = self.bill_manage_server.add_bill(
                OperationType.update.value, TypeId.allowance.value, allowance_define, 'PT_Allowance_Define')
            if bill_id:
                res = 'Success'
        else:
            allowance_define['create_time'] = datetime.datetime.now()
            data_info = get_info(allowance_define, self.session)
            bill_id = self.bill_manage_server.add_bill(
                OperationType.add.value, TypeId.allowance.value, data_info, 'PT_Allowance_Define')
            if bill_id:
                res = 'Success'
        return res

    def get_allowance_define_list(self, org_list, condition, page=None, count=None):
        '''查询补贴定义列表'''
        keys = ['id', 'name', 'template_name', 'create_time', 'start', 'end']
        if 'create_time' in list(condition.keys()):
            condition['start'] = condition['create_time'][0]
            condition['end'] = condition['create_time'][1]
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.lookup_bill('PT_Assessment_Template', 'template_id', 'id', 'template')\
            .add_fields({'template_name': '$template.template_name'})\
            .match_bill((C('template_name') == values['template_name'])
                        & (C('name') == values['name'])
                        & (C('create_date') >= as_date(values['start']))
                        & (C('create_date') <= as_date(values['end']))
                        & (C('organization_id').inner(org_list))
                        & (C('id') == values['id']))\
            .project({'_id': 0, 'template._id': 0})
        res = self.page_query(_filter, 'PT_Allowance_Define', page, count)
        return res

    def del_allowance_define(self, ids):
        '''删除补贴定义'''
        res = 'Fail'
        for i in ids:
            _filter = MongoBillFilter()
            _filter.match((C('template') == i)).project({'_id': 0})
            res = self.query(_filter, "PT_Allowance_Manage")
            if len(res) > 0:
                res = '该补贴定义已被引用，无法删除'
            else:
                bill_id = self.bill_manage_server.add_bill(
                    OperationType.delete.value, TypeId.allowance.value, {'id': i}, 'PT_Allowance_Define')
                if bill_id:
                    res = 'Success'
        return res

    def subsidy_approval(self, subsidy_data):
        '''审批补贴 subsidy_data:{id:'',subsidy_res:'',opinion{}} '''
        res = 'Fail'

        def process_func(db):
            nonlocal res
            persion_id = get_current_user_id(self.session)
            # 查询补贴单据数据
            if 'id' in subsidy_data.keys():
                allowance_id = subsidy_data['id']
                _filter = MongoBillFilter()
                _filter.match_bill((C('id') == allowance_id)
                                   ).project({'_id': 0})
                allowance_data = self.query(_filter, self.Allowance)
                if len(allowance_data) > 0:
                    allowance = allowance_data[0]
                    # 查询过程表数据
                    # process_data = find_data(db, 'PT_Approval_Process', {
                    #     'business_id': allowance_id, 'approval_user_id': persion_id, 'step_no': allowance['step_no']})
                    _filter_process = MongoBillFilter()
                    _filter_process.match_bill((C('business_id') == allowance_id) & (
                        C('approval_user_id') == persion_id) & (C('step_no') == allowance['step_no'])).project({'_id': 0})
                    process_data = self.query(
                        _filter_process, 'PT_Approval_Process')
                    if len(process_data) > 0 and 'subsidy_res' in subsidy_data.keys() and 'opinion' in subsidy_data.keys():
                        # 获取审批结果
                        subsidy_res = subsidy_data['subsidy_res']
                        process = process_data[0]
                        process['opinion'] = []
                        process['opinion'].append(subsidy_data['opinion'])
                        if subsidy_res == '通过':
                            process['status'] = '通过'
                            # 判断是否最后一步，最后一步则完结业务单据状态且step_no改为空,不是最后一步则把step_no改为下一步
                            _filter_process_length = MongoBillFilter()
                            _filter_process_length.match_bill(
                                (C('business_id') == allowance_id)).project({'_id': 0})
                            process_data_length = len(self.query(
                                _filter_process_length, 'PT_Approval_Process'))
                            # process_data_length = len(
                            #     find_data(db, 'PT_Approval_Process', {'business_id': allowance_id}))
                            if allowance['step_no'] > 0 and process_data_length == allowance['step_no']:
                                # 最后一步
                                allowance['status'] = '通过'
                                allowance['allowance_money'] = subsidy_data['allowance_money']
                                allowance['step_no'] = -1
                                # 往中间表插入相关数据
                                if allowance['allowance_type'] != "就业补贴" and allowance['allowance_type'] != "岗位补贴":
                                    record_data = {"user_id": allowance['apply_user_id'], "amount": subsidy_data['allowance_money'],
                                                   "subsidy_type": SubsidyRecordSubsidyType.Seniors,
                                                   "begin_date": datetime.datetime(datetime.datetime.now().year, datetime.datetime.now().month + 1, 1, 0, 0, 0),
                                                   "end_date": datetime.datetime(datetime.datetime.now().year+1, datetime.datetime.now().month, 1, 23, 59, 59)-datetime.timedelta(days=1),
                                                   "state": SubsidyRecordState.valid}
                                    record_data_list = []
                                    record_data_list.append(
                                        get_info(record_data, self.session))
                                    bill_id = self.bill_manage_server.add_bill(
                                        OperationType.add.value, TypeId.allowanceSubsidy.value, record_data_list, ['PT_Subsidy_Record'])
                            elif allowance['step_no'] > 0 and process_data_length > allowance['step_no']:
                                # 非最后一步
                                allowance['status'] = '审批中'
                                allowance['step_no'] = allowance['step_no'] + 1
                            else:
                                return '无法重复审批'
                        if subsidy_res == '不通过':
                            process['status'] = '不通过'
                            # 把业务单据的状态改为不通过
                            allowance['status'] = '不通过'
                        if subsidy_res == '打回':
                            process['status'] = '打回'
                            allowance['status'] = '打回'
                        # 修改业务表和过程表
                        data = [allowance, process]
                        bill_id = self.bill_manage_server.add_bill(OperationType.update.value, TypeId.allowanceSubsidy.value, data, [
                            self.Allowance, 'PT_Approval_Process'])
                        if bill_id:
                            res = 'Success'
            else:
                res = '补贴单据Id不能为空'

        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res

    def add_allowance_project(self, allowance):
        '''新增或修改补贴项目'''
        res = 'Fail'
        print(allowance)
        if 'id' in allowance.keys():
            bill_id = self.bill_manage_server.add_bill(
                OperationType.update.value, TypeId.allowance.value, allowance, 'PT_Allowance_Project')
            if bill_id:
                res = 'Success'
        else:
            allowance['create_time'] = datetime.datetime.now()
            data_info = get_info(allowance, self.session)
            bill_id = self.bill_manage_server.add_bill(
                OperationType.add.value, TypeId.allowance.value, data_info, 'PT_Allowance_Project')
            if bill_id:
                res = 'Success'
        return res

    def get_allowance_project_list(self, allowance, page=None, count=None):
        '''查询补贴项目'''
        keys = ['id', 'name', 'type', 'create_date']
        values = self.get_value(allowance, keys)
        start = N()
        end = N()
        if(bool(1-isinstance(values['create_date'], N))):
            start = values['create_date']+"T00:00:00.00Z"
            end = values['create_date']+"T23:59:59.00Z"
        _filter = MongoBillFilter()
        _filter.match_bill((C('id') == values['id'])
                           & (C('allowance_project_name').like(values['name']))
                           & (C('allowance_project_type') == values['type'])
                           & (C('create_date') > as_date(start))
                           & (C('create_date') < as_date(end)))\
               .lookup_bill('PT_Allowance_Manage', 'id', 'project_id', 'sq_list')\
               .add_fields({'sq_num': self.ao.size('$sq_list')})\
            .project({'_id': 0, 'sq_list._id': 0})
        res = self.page_query(_filter, 'PT_Allowance_Project', page, count)
        return res

    def del_allowance_project(self, ids):
        '''查询补贴项目'''
        res = 'Fail'
        for i in ids:
            bill_id = self.bill_manage_server.add_bill(
                OperationType.delete.value, TypeId.allowance.value, {'id': i}, 'PT_Allowance_Project')
        if bill_id:
            res = 'Success'
        return res

    def get_reviewed_idea(self, condition, page=None, count=None):
        '''查询每一步审批的意见'''
        res = 'Fail'
        keys = ['business_id']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('business_id') == values['business_id']))\
            .project({'_id': 0})
        res = self.page_query(_filter, "PT_Approval_Process", page, count)
        return res

    def user_identification(self, condition):
        # # 高原补贴活体认证
        global photo_base64, img_res
        res = '活体验证失败'
        # keys = ["id_card","name","idStartDate","idEndDate","photo"]
        # values = self.get_value(condition, keys)
        try:
            img = ImageSize(
                (r".{}".format(condition['photo'][0])), (r".{}".format(condition['photo'][0])))
            # jpgpath = img.to_jpg(r".{}".format(condition['photo'][0]))
            img.resize_image()
            img_res = img.compress_image()
        except Exception as e:
            print(e)
        with open((r".{}".format(condition['photo'][0])), 'rb') as f:
            # with open(img_res[0]), 'rb') as f:
            base64_data = base64.b64encode(f.read())
            photo_base64 = base64_data.decode()
        # 第一步：获取接入凭证
        url = 'https://api.auth.dabby.cn/getaccesstoken?clientId=971804c4ddc0ae6e&clientSecret=e179ec8d-5882-4bfc-8f28-3ecfe37db0e5'
        token_res = requests.get(url)
        token = token_res.json()['accessToken']
        state = token_res.json()['retCode']
        if state == 0:
            # 第二步：进行一次身份认证，提交身份认证信息，获取认证结果
            url_x = 'https://api.auth.dabby.cn/simpauth'
            params = json.dumps({"accessToken": token, "authData": {"mode": 66, "idInfo": {
                                "idNum": condition['id_card_num'], "fullName": condition['name']}, "portrait": photo_base64}})
            # prin t(params)
            headers = {"Content-Type": "application/json; charset=UTF-8"}
            result = requests.post(url_x, data=params, headers=headers).json()
            print("大白数据》》》》》》》》》》》》", result)
            if result['retCode'] == 0:
                # 第三步：根据返回的结果进行判断，并像前端返回结果信息
                resStr = result['resStr']
                if resStr[0] == "0":
                    print("身份信息有效")
                    res = "身份信息有效"
                    if resStr[1] == "0":
                        # "身份信息与上传照片是同一人"
                        res = "Success"
                    if resStr[1] == "1":
                        res = "身份信息与上传照片非同一人"
                    if resStr[1] == "2":
                        res = "疑似为本人(1.照片可能有角度，光线过暗，脸部区域有亮斑，模糊 ；2.照片尺寸太小； 3.两人长相相似)"
                elif resStr[0] == "5":
                    res = "身份信息未查到"
            elif result['retCode'] == 4109:
                res = '非库内人员：该人员身份信息未收录，无法完成身份认证'
            elif result['retCode'] == 4101:
                res = '身份认证不通过'
        else:
            res = '服务错误'
        return res

    def insert_allowance(self, values, insert_data):
        id_card_info = {
            'id_card': values['id_card_num'],
            'name': values['name'],
            # 'idStartDate':values['card_start_date'],
            # 'idEndDate':values['card_end_date'],
            'photo': values['photo']
        }
        res = self.user_identification(id_card_info)
        if res == 'Success':
            insert_data['apply_status'] = '认证成功'
            data_info = get_info(insert_data, self.session)
            print(data_info)
            bill_id = self.bill_manage_server.add_bill(
                OperationType.add.value, TypeId.allowance.value, data_info, 'PT_Old_Age_Allowance')
            if bill_id:
                res = '认证成功'
            return res
        else:
            return res

    def apply_old_age_allowance(self, condition):
        '''高龄津贴申请
        condition {dict}   津贴申请信息
        conditon = {"name" : 姓名, 
                    "id_card_num" : 身份证号,  
                    "photo" : 本人照片}
        '''
        if 'type' in condition.keys():
            keys = ['name', 'id_card_num', 'photo']
            print("照片》》》》》》》》》》》》", condition['photo'])
            insert_data = {
                'name': condition['name'],
                'id_card_num': condition['id_card_num'],
                'photo': condition['photo']
            }
            # 判断本月是否已经成功认证过了
            print("当前月份/////////////////", datetime.datetime.now().month)
            if datetime.datetime.now().month < 12:
                print(222222222222222222222222)
                start = datetime.datetime(datetime.datetime.now(
                ).year, datetime.datetime.now().month, 1, 0, 0, 0)
                end = datetime.datetime(datetime.datetime.now().year, datetime.datetime.now(
                ).month + 1, 1, 23, 59, 59)-datetime.timedelta(days=1)
                print(start)
                print(end)
            else:
                print(1111111111111111111111111111111111111)
                start = datetime.datetime(datetime.datetime.now(
                ).year, datetime.datetime.now().month, 1, 0, 0, 0)
                print(start)
                end = datetime.datetime(datetime.datetime.now(
                ).year + 1, 1, 1, 23, 59, 59)-datetime.timedelta(days=1)
                print(end)
            _filter = MongoBillFilter()
            _filter.match_bill((C('id_card_num') == condition['id_card_num'])
                               & (C('create_date') >= start)
                               & (C('create_date') <= end))\
                .project({'_id': 0})
            record_res = self.query(_filter, "PT_Old_Age_Allowance")
            if len(record_res) > 0:
                return [{'result': '你本月已完成认证，无需重复操作'}]
            else:
                # 在申请成功之前去记录表里查询是否存在这个人，如果有就申请成功，如果没有就打回
                _filter = MongoBillFilter()
                _filter.match((C('name') == condition['name']) & (C('id_card_num') == condition['id_card_num']))\
                    .project({'_id': 0})
                md_res = self.query(_filter, "PT_Old_Age_List")
                print(1111111111111111)
                print("名单数据》》》》》》》》》》》》》》》", md_res)
                if len(md_res) > 0:
                    try:
                        # 调用大白
                        res = self.user_identification(insert_data)
                    except:
                        return [{'result': '人脸认证异常'}]
                    finally:
                        if len(condition['photo']) > 0:
                            try:
                                path = (r".{}".format(condition['photo'][0]))
                                # 删除照片
                                os.remove(path)
                            except Exception as e:
                                print(e)
                    print(3333333333333333333333333333333)
                    if res == 'Success':
                        print(444444444444444444444444444444)
                        insert_data['apply_status'] = '认证成功'
                        insert_data['id'] = str(uuid.uuid1())
                        insert_data['create_date'] = datetime.datetime.now()
                        insert_data['modify_date'] = datetime.datetime.now()
                        # 把名单表的数据插入到认证申请这里
                        insert_data['amount'] = md_res[0]['amount']
                        insert_data['town_street'] = md_res[0]['amount']
                        insert_data['village'] = md_res[0]['village']
                        insert_data['sex'] = md_res[0]['sex']
                        insert_data['bank_card_num'] = md_res[0]['bank_card_num']
                        insert_data['replacement_amount'] = md_res[0]['replacement_amount']
                        insert_data['total_amount'] = md_res[0]['total_amount']
                        print(insert_data)
                        bill_id = self.bill_manage_server.add_bill(
                            OperationType.add.value, TypeId.allowance.value, insert_data, 'PT_Old_Age_Allowance')
                        if bill_id:
                            print(555555555555555555555555555555555555)
                            return [{'result': '认证成功'}]
                        else:
                            print(
                                6666666666666666666666666666666666666666666666666666666666)
                            return [{'result': '认证失败'}]
                    else:
                        # 活体验证接口认证失败
                        insert_data['reason'] = res
                        insert_data['id'] = str(uuid.uuid1())
                        insert_data['create_date'] = datetime.datetime.now()
                        insert_data['modify_date'] = datetime.datetime.now()
                        print(insert_data)
                        bill_id = self.bill_manage_server.add_bill(
                            OperationType.add.value, TypeId.allowance.value, insert_data, 'PT_Old_Age_Failed')
                        if bill_id:
                            print(77777777777777777777777777777777777777777777777)
                            return [{'result': res}]
                else:
                    print(8888888888888888888888888888888888888888888888)
                    # 名单表里没有这个老人，往不通过表里面插数据
                    insert_data['reason'] = '津贴名单中没有此人员的相关信息，认证失败'
                    insert_data['id'] = str(uuid.uuid1())
                    insert_data['create_date'] = datetime.datetime.now()
                    insert_data['modify_date'] = datetime.datetime.now()
                    print(insert_data)
                    bill_id = self.bill_manage_server.add_bill(
                        OperationType.add.value, TypeId.allowance.value, insert_data, 'PT_Old_Age_Failed')
                    if bill_id:
                        return [{'result': '津贴名单中没有此人员的相关信息，认证失败'}]
        else:
            insert_data = {
                'id_card_num': condition['id_card_num'],
            }
            # 判断本月是否已经成功认证过了
            if datetime.datetime.now().month < 12:
                start = datetime.datetime(datetime.datetime.now(
                ).year, datetime.datetime.now().month, 1, 0, 0, 0)
                end = datetime.datetime(datetime.datetime.now().year, datetime.datetime.now(
                ).month + 1, 1, 23, 59, 59)-datetime.timedelta(days=1)
            else:
                start = datetime.datetime(datetime.datetime.now(
                ).year, datetime.datetime.now().month, 1, 0, 0, 0)
                end = datetime.datetime(datetime.datetime.now(
                ).year + 1, 1, 1, 23, 59, 59)-datetime.timedelta(days=1)
            _filter = MongoBillFilter()
            _filter.match_bill((C('id_card_num') == condition['id_card_num'])
                               & (C('create_date') >= start)
                               & (C('create_date') <= end))\
                .project({'_id': 0})
            record_res = self.query(_filter, "PT_Old_Age_Allowance")
            if len(record_res) > 0:
                return [{'result': '你本月已完成认证，无需重复操作'}]
            else:
                # 在申请成功之前去记录表里查询是否存在这个人，如果有就申请成功，如果没有就打回
                _filter = MongoBillFilter()
                _filter.match((C('id_card_num') == condition['id_card_num']))\
                    .project({'_id': 0})
                md_res = self.query(_filter, "PT_Old_Age_List")
                if len(md_res) > 0:
                    if condition['status'] == 0:
                        print(55555555555)
                        insert_data['apply_status'] = '认证成功'
                        insert_data['id'] = str(uuid.uuid1())
                        insert_data['create_date'] = datetime.datetime.now()
                        insert_data['modify_date'] = datetime.datetime.now()
                        # 把名单表的数据插入到认证申请这里
                        insert_data['amount'] = md_res[0]['amount']
                        insert_data['name'] = md_res[0]['name']
                        insert_data['town_street'] = md_res[0]['town_street']
                        insert_data['village'] = md_res[0]['village']
                        insert_data['sex'] = md_res[0]['sex']
                        insert_data['bank_card_num'] = md_res[0]['bank_card_num']
                        insert_data['replacement_amount'] = md_res[0]['replacement_amount']
                        insert_data['total_amount'] = md_res[0]['total_amount']
                        print(insert_data)
                        bill_id = self.bill_manage_server.add_bill(
                            OperationType.add.value, TypeId.allowance.value, insert_data, 'PT_Old_Age_Allowance')
                        if bill_id:
                            return [{'result': '认证成功'}]
                        else:
                            return [{'result': '认证失败'}]
                    else:
                        # 活体验证接口认证失败
                        insert_data['reason'] = res
                        insert_data['id'] = str(uuid.uuid1())
                        insert_data['create_date'] = datetime.datetime.now()
                        insert_data['modify_date'] = datetime.datetime.now()
                        bill_id = self.bill_manage_server.add_bill(
                            OperationType.add.value, TypeId.allowance.value, insert_data, 'PT_Old_Age_Failed')
                        if bill_id:
                            return [{'result': res}]
                else:
                    # 名单表里没有这个老人，往不通过表里面插数据
                    insert_data['reason'] = '津贴名单中没有此人员的相关信息，认证失败'
                    insert_data['id'] = str(uuid.uuid1())
                    insert_data['create_date'] = datetime.datetime.now()
                    insert_data['modify_date'] = datetime.datetime.now()
                    print(insert_data)
                    bill_id = self.bill_manage_server.add_bill(
                        OperationType.add.value, TypeId.allowance.value, insert_data, 'PT_Old_Age_Failed')
                    if bill_id:
                        return [{'result': '津贴名单中没有此人员的相关信息，认证失败'}]

    def get_old_age_allowance_status(self, condition):
        '''
        查询高龄津贴申请状态查询
        '''
        if 'time' in condition.keys():
            start = datetime.datetime.now()
            end = datetime.datetime.now()
            if as_date(condition['time']).month < 12:
                start = datetime.datetime(as_date(condition['time']).year, as_date(
                    condition['time']).month, 1, 0, 0, 0)
                end = datetime.datetime(as_date(condition['time']).year, as_date(
                    condition['time']).month + 1, 1, 23, 59, 59)-datetime.timedelta(days=1)
            else:
                start = datetime.datetime(as_date(condition['time']).year, as_date(
                    condition['time']).month, 1, 0, 0, 0)
                end = datetime.datetime(as_date(
                    condition['time']).year + 1, 1, 1, 23, 59, 59)-datetime.timedelta(days=1)
            print("传过来的时间》》》》》》》》", as_date(condition['time']).month)
            print(start)
            print(end)
            keys = ['id_card_num']
            values = self.get_value(condition, keys)
            _filter = MongoBillFilter()
            _filter.match_bill((C('id_card_num') == values['id_card_num'])
                               & (C('create_date') >= start)
                               & (C('create_date') <= end)
                               & (C('apply_status') == '已生成台账'))\
                .project({'_id': 0})
            time_res = self.query(_filter, "PT_Old_Age_Allowance")
            print(time_res)
            if len(time_res) > 0:
                result = time_res[0]
            else:
                result = '你本月还未有发放记录'
            return result
        elif 'rz_status' in condition.keys():
            # 判断60天内是否已经成功认证过了
            keys = ['id_card_num']
            values = self.get_value(condition, keys)
            _filter = MongoBillFilter()
            _filter.match_bill(C('id_card_num') == condition['id_card_num'])\
                .sort({'create_date': -1})\
                .project({'_id': 0})
            record_res = self.query(_filter, "PT_Old_Age_Allowance")
            if len(record_res) > 0:
                print((datetime.datetime.now() -
                       record_res[0]['create_date']).days)
                if (datetime.datetime.now() - record_res[0]['create_date']).days < 60:
                    return '60天内已认证'
                else:
                    return '未认证'
            else: 
                return '该长者不在名单表中'
        elif 'year' in condition.keys():
            print(condition['year'])
            start = datetime.datetime(int(condition['year']), 1, 1, 0, 0, 0)
            end = datetime.datetime(
                int(condition['year'] + 1), 1, 1, 23, 59, 59)-datetime.timedelta(days=1)
            print(start)
            print(end)
            _filter = MongoBillFilter()
            _filter.match_bill((C('id_card_num') == condition['id_card_num'])
                               & (C('create_date') >= start)
                               & (C('create_date') <= end))\
                .project({'_id': 0})
            year_res = self.query(_filter, "PT_Old_Age_Allowance")
            if len(year_res) > 0:
                result = year_res
            else:
                result = []
            return result
        else:
            keys = ['id_card_num']
            values = self.get_value(condition, keys)
            start = datetime.datetime.now()
            end = datetime.datetime.now()
            print(condition['month'])
            if int(condition['month']) + 1 < 12:
                print(222222222222222222222222)
                start = datetime.datetime(datetime.datetime.now(
                ).year, int(condition['month']) + 1, 1, 0, 0, 0)
                end = datetime.datetime(datetime.datetime.now(
                ).year, condition['month'] + 2, 1, 23, 59, 59)-datetime.timedelta(days=1)
                print(start)
                print(end)
            else:
                print(1111111111111111111111111111111111111)
                start = datetime.datetime(datetime.datetime.now(
                ).year, int(condition['month']) + 1, 1, 0, 0, 0)
                print(start)
                end = datetime.datetime(datetime.datetime.now(
                ).year + 1, 1, 1, 23, 59, 59)-datetime.timedelta(days=1)
                print(end)
            _filter = MongoBillFilter()
            _filter.match_bill((C('id_card_num') == values['id_card_num'])
                               & (C('create_date') >= start)
                               & (C('create_date') <= end))\
                .project({'_id': 0})
            month_res = self.query(_filter, "PT_Old_Age_Allowance")
            print("数据》》》》》》》》》》》", month_res)
            if len(month_res) > 0:
                result = month_res[0]
            else:
                result = '你本月还未有认证记录'
            return result

    def audit_old_allowance(self, condition):
        '''
        审核高龄津贴申请
        condition {dict} 审核结果
        condition = {
            apply_status:  已发放（通过）/ 未通过
            id:高龄津贴id
            (ic_card_num:身份证号码)
        }
        '''
        keys = ['id', 'id_card_num']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('id') == values['id'])
                           & (C('id_card_num') == values['id_card_num'])
                           & (C('apply_status') == '审核中')).project({'_id': 0})
        res = self.query(_filter, 'PT_Old_Age_Allowance')
        if res:
            _filter = MongoBillFilter()
            _filter.match((C('id_card_num') == values['id_card_num'])).project(
                {'_id': 0})
            money_res = self.query(_filter, "PT_Old_Age_List")
            insert_dict = {
                "amount": money_res[0]['amount'],
                'apply_status': condition.get('apply_status'),
                'id': res[0].get('id'),
                'audit_time': datetime.datetime.now(),
                'audit_user_id': get_current_user_id(self.session),
            }
            bill_id = self.bill_manage_server.add_bill(OperationType.update.value,
                                                       TypeId.allowance.value, insert_dict, 'PT_Old_Age_Allowance')
            if bill_id:
                return "Success"
            return "Fail"
        return '该高龄津贴申请不存在'

    def get_audit_old_allowance_list(self, org_list, condition, page, count):
        '''
        获取高龄津贴审核列表
        '''
        keys = ['name', 'status', 'id_card_num', 'start_time',
                'end_time', 'village', 'town_street', 'start_age', 'end_age']
        # print(11111111111111111111111111111111111111111)
        # print(as_date(condition['start_time']))
        # print(as_date(condition['end_time']))
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.add_fields({'status': '认证成功'})\
            .match((C('name') == values['name'])
                   & (C('create_date') >= as_date(values['start_time']))
                   & (C('create_date') <= as_date(values['end_time']))
                   & (C('id_card_num') == values['id_card_num'])
                   & (C('apply_status') == values['status'])
                   & (C('village') == values['village'])
                   & (C('age') >= values['start_age'])
                   & (C('age') <= values['end_age'])
                   & (C('town_street') == values['town_street']))\
            .project({'_id': 0})
        res = self.page_query(_filter, 'PT_Old_Age_Allowance', page, count)
        # print("导出数据》》》》》》",res)
        return res

        # for data in res['result']:
        #     print('-------------------------------------------------------',data)
        #     if 'id_card_num' in data.keys():
        #         print(data['id_card_num'])
        #         _filter = MongoBillFilter()
        #         _filter.match((C('id_card_num') == data['id_card_num'])
        #                     & (C('village') == values['village'])
        #                     & (C('age') >= values['start_age'])
        #                     & (C('age') <= values['end_age'])
        #                     & (C('town_street') == values['town_street']))\
        #             .project({'_id':0})
        #         export_res = self.page_query(_filter,'PT_Old_Age_List', page, count)
        #         print('8-+++++++++++++++++++++++++++++++++++++++++++',export_res)
        #         if len(export_res['result']) > 0:
        #             export_res['result'][0]['status'] = '认证成功'
        #             export_data['total'] = int(export_data['total']) + 1
        #             export_data['result'].append(export_res['result'][0])
        #         else:
        #             export_data = {'total': 0, 'result': []}
        #         print("数据???????????????????",export_data)
        # keys = ['id','id_card_num']
        # values = self.get_value(condition,keys)
        # _filter = MongoBillFilter()
        # _filter.match_bill((C('id') == values['id'])
        #     # & (C('organization_id').inner(org_list))
        #     & (C('id_card_num') == values['id_card_num'])
        #     & (C('apply_status') == '认证成功')).project({'_id':0})
        # res = self.page_query(_filter,'PT_Old_Age_Allowance', page, count)
        # return res

    def get_old_age_list(self, org_list, condition, page, count):
        '''
            获取高龄津贴名单列表
        '''
        keys = ['id', 'name', 'id_card_num', 'town_street', 'village']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match((C('id') == values['id'])
                      & (C('id_card_num') == values['id_card_num'])
                      & (C('name') == values['name'])
                      & (C('town_street').like(values['town_street']))
                      & (C('village').like(values['village'])))\
            .project({'_id': 0})
        res = self.page_query(_filter, 'PT_Old_Age_List', page, count)
        return res

    def upload_old_age_list(self, data):
        '''
            高龄津贴导入方法
        '''
        # 从excel表的第三行开始取值
        pf = pd.DataFrame(data[1:])
        pf.rename(columns={'__EMPTY': 'town_street', '__EMPTY_1': 'village', '__EMPTY_2': 'name', '__EMPTY_3': 'sex', '__EMPTY_4': 'id_card_num', '__EMPTY_5': 'age',
                           '__EMPTY_6': 'bank_card_num', '__EMPTY_7': 'amount', '__EMPTY_8': 'replacement_amount', '__EMPTY_9': 'total_amount', '当前享受高龄津贴明细': 'title'}, inplace=True)
        pf = pf.drop(['age', 'title'], axis=1)
        condition = dataframe_to_list(pf)
        if len(condition) > 0:
            town_street = [condition[0]['town_street']]
            village = [condition[0]['village']]
            for i, x in enumerate(condition):
                x = get_info(x, self.session)
                x['amount'] = float(x['amount'])
                # x['age'] = float(x['age'])
                x['replacement_amount'] = float(x['replacement_amount'])
                x['total_amount'] = float(x['total_amount'])
                if x['town_street'] not in town_street:
                    town_street.append(x['town_street'])
                if x['village'] not in village:
                    village.append(x['village'])
                # def process_func(db):
                #     insert_many_data(db, 'PT_Old_Age_List', x)
                # try:
                #     process_db(self.db_addr, self.db_port, self.db_name, process_func)
                # except:
                #     raise JsonRpc2Error(-36109,'第'+str(i+3)+'行出错')

            def process_func(db):
                insert_many_data(db, 'PT_Old_Age_List', condition)

            def process_func_del(db):
                delete_data(db, 'PT_Old_Age_List', {'town_street': {
                            "$in": town_street}, 'village': {"$in": village}})
            try:
                # 删除该镇街的原有数据（批量删除）
                process_db(self.db_addr, self.db_port, self.db_name,
                           process_func_del, self.db_user, self.db_pwd)
                # 插入新的excel表信息（批量）
                process_db(self.db_addr, self.db_port, self.db_name,
                           process_func, self.db_user, self.db_pwd)
            except Exception as e:
                raise JsonRpc2Error(-36109, e)
            # 插入新表数据（根据镇街、乡、月份、年龄段长者汇总）
            # 当前年份
            current_year = get_cur_time().year
            # 当前月份
            current_month = get_cur_time().month
            # 年月
            month_year = str(current_year)+str(current_month)
            # 查询名单表的信息
            _filter = MongoBillFilter()
            _filter.add_fields({'year': self.ao.to_int(self.ao.sub_str('$id_card_num', 6, 4))})\
                .add_fields({'age': ((F('year')-current_year)*(-1)).f})\
                .add_fields({
                    's_elder_quantity': self.ao.switch([self.ao.case(((F('age') >= 70) & (F('age') < 80)), 1)], 0),
                    'e_elder_quantity': self.ao.switch([self.ao.case(((F('age') >= 80) & (F('age') < 90)), 1)], 0),
                    'n_elder_quantity': self.ao.switch([self.ao.case(((F('age') >= 90) & (F('age') < 100)), 1)], 0),
                    'h_elder_quantity': self.ao.switch([self.ao.case(((F('age') >= 100)), 1)], 0),
                    'elder_total_quantity': 1,
                    'month': month_year})\
                .group(
                {
                    'town_street': '$town_street',
                    'village': '$village',
                    'month': '$month'
                },
                [{
                    'elder_total_quantity': self.ao.summation('$elder_total_quantity')
                },
                    {
                    's_elder_quantity': self.ao.summation('$s_elder_quantity')
                },
                    {
                    'e_elder_quantity': self.ao.summation('$e_elder_quantity')
                },
                    {
                    'n_elder_quantity': self.ao.summation('$n_elder_quantity')
                },
                    {
                    'h_elder_quantity': self.ao.summation('$h_elder_quantity')
                }])\
                .sort({'month': 1, 'town_street': 1, 'village': 1})\
                .project({'_id': 0})
            statistics = self.query(_filter, 'PT_Old_Age_List')

            def process_func_statistics(db):
                insert_many_data(db, 'PT_Old_Age_Statistics', statistics)

            def process_func_del_statistics(db):
                delete_data(db, 'PT_Old_Age_Statistics', {'month': month_year})
            # 根据月份删除旧数据
            process_db(self.db_addr, self.db_port, self.db_name,
                       process_func_del_statistics, self.db_user, self.db_pwd)
            # 插入新的数据
            process_db(self.db_addr, self.db_port, self.db_name,
                       process_func_statistics, self.db_user, self.db_pwd)

        return ResultData('0', '成功导入'+str(len(condition))+'行数据', []).to_dict()

    def get_old_age_statistics(self, condition):
        ''' 高龄津贴统计报表'''
        res = {'result': []}
        keys = ['month']
        values = self.get_value(condition, keys)
        # 当前年份
        current_year = get_cur_time().year
        # 查询认证申请表的信息
        _filter = MongoBillFilter()
        if 'month' in condition.keys() and len(values['month']) == 6:
            # str类型,格式：yyyymm
            month = int(values['month'][4:])
            year = int(values['month'][0:4])
            print('year>>>', year)
            start = datetime.datetime.now()
            end = datetime.datetime.now()
            if month < 12:
                start = datetime.datetime(year, month, 1, 0, 0, 0)
                end = datetime.datetime(
                    year, month + 1, 1, 23, 59, 59)-datetime.timedelta(days=1)
            else:
                start = datetime.datetime(year, month, 1, 0, 0, 0)
                end = datetime.datetime(
                    year + 1, 1, 1, 23, 59, 59)-datetime.timedelta(days=1)
            _filter.match_bill((C('create_date') > start)
                               & (C('create_date') < end))
        _filter.add_fields({'current_year': self.ao.to_string(self.ao.year('$create_date'))})\
               .add_fields({'current_month': self.ao.to_string(self.ao.month('$create_date'))})\
               .add_fields({'month': self.ao.concat([('$current_year'), ('$current_month')]), 'year': self.ao.to_int(self.ao.sub_str('$id_card_num', 6, 4))})\
               .add_fields({'age': ((F('year')-current_year)*(-1)).f})\
               .add_fields({
                   's_elder_authentication_quantity': self.ao.switch([self.ao.case(((F('age') >= 70) & (F('age') < 80)), 1)], 0),
                   'e_elder_authentication_quantity': self.ao.switch([self.ao.case(((F('age') >= 80) & (F('age') < 90)), 1)], 0),
                   'n_elder_authentication_quantity': self.ao.switch([self.ao.case(((F('age') >= 90) & (F('age') < 100)), 1)], 0),
                   'h_elder_authentication_quantity': self.ao.switch([self.ao.case(((F('age') >= 100)), 1)], 0),
                   'elder_authentication_total_quantity': 1})\
            .project({'name': 1, 'id_card_num': 1, 'town_street': 1, 'village': 1, 'month': 1, 's_elder_authentication_quantity': 1, 'e_elder_authentication_quantity': 1, 'n_elder_authentication_quantity': 1, 'h_elder_authentication_quantity': 1, 'elder_authentication_total_quantity': 1})\
            .group(
            {
                'name': '$name',
                        'id_card_num': '$id_card_num',
                        'town_street': '$town_street',
                        'village': '$village',
                        'month': '$month',
                        's_elder_authentication_quantity': '$s_elder_authentication_quantity',
                        'e_elder_authentication_quantity': '$e_elder_authentication_quantity',
                        'n_elder_authentication_quantity': '$n_elder_authentication_quantity',
                        'h_elder_authentication_quantity': '$h_elder_authentication_quantity',
                        'elder_authentication_total_quantity': '$elder_authentication_total_quantity'
            },
            [{
                'self_authentication_quantity': self.ao.summation(1)
            }])\
            .group(
            {
                'town_street': '$town_street',
                'village': '$village',
                'month': '$month',
            },
            [{
                'elder_authentication_total_quantity': self.ao.summation('$elder_authentication_total_quantity')
            },
                {
                's_elder_authentication_quantity': self.ao.summation('$s_elder_authentication_quantity')
            },
                {
                'e_elder_authentication_quantity': self.ao.summation('$e_elder_authentication_quantity')
            },
                {
                'n_elder_authentication_quantity': self.ao.summation('$n_elder_authentication_quantity')
            },
                {
                'h_elder_authentication_quantity': self.ao.summation('$h_elder_authentication_quantity')
            }])
        res_old_age = self.query(_filter, 'PT_Old_Age_Allowance')
        # print('res_old_age>>>',res_old_age)
        # # 查询名单表的信息
        _filter = MongoBillFilter()
        _filter.match((C('month') == values['month']))\
               .sort({'month': 1, 'town_street': 1, 'village': 1})\
               .project({'_id': 0})
        res_list = self.query(_filter, 'PT_Old_Age_Statistics')
        # print('res_list>>>',res_list)
        pf_old_age = pd.DataFrame(res_old_age)
        pf_list = pd.DataFrame(res_list)
        new_pd = pd.merge(pf_list, pf_old_age, how='left', on=[
                          'town_street', 'village', 'month'])
        new_pd[['elder_authentication_total_quantity', 's_elder_authentication_quantity', 'e_elder_authentication_quantity', 'n_elder_authentication_quantity', 'h_elder_authentication_quantity']] = new_pd[[
            'elder_authentication_total_quantity', 's_elder_authentication_quantity', 'e_elder_authentication_quantity', 'n_elder_authentication_quantity', 'h_elder_authentication_quantity']].fillna(value=0)
        new_pd['elder_uncertified_total_quantity'] = new_pd['elder_total_quantity'] - \
            new_pd['elder_authentication_total_quantity']
        new_pd['elder_complete_percent_total_quantity'] = new_pd.apply(lambda x: str(
            x.elder_authentication_total_quantity*100/x.elder_total_quantity) + '%' if x.elder_authentication_total_quantity != 0 else '0%', axis=1)
        result = dataframe_to_list(new_pd)
        res['result'] = result
        return res

    def get_certToken(self, condition):
        # 第一步：获取接入凭证
        url = 'https://rz.weijing.gov.cn/v2/api/getaccesstoken?clientId=bc1f8617b6e2d2b2&clientSecret=8edf0aae-8b0b-4b86-8b80-bbdcbe5f386a'
        token_res = requests.get(url)
        token = token_res.json()['accessToken']
        state = token_res.json()['retCode']
        if state == 0:
            # 第一步：获取接入凭证
            url_x = 'https://rz.weijing.gov.cn/v2/api/authreq'
            params = json.dumps({"accessToken": token, "authType": "GzhRegular", "extraParams": {
                                "foreBackUrl": condition['url']}})
            headers = {"Content-Type": "application/json; charset=UTF-8"}
            result = requests.post(url_x, data=params, headers=headers).json()
            return result

    def get_rz_result(self, condition):
        # 第一步：获取接入凭证
        url = 'https://rz.weijing.gov.cn/v2/api/getaccesstoken?clientId=bc1f8617b6e2d2b2&clientSecret=8edf0aae-8b0b-4b86-8b80-bbdcbe5f386a'
        token_res = requests.get(url)
        token = token_res.json()['accessToken']
        state = token_res.json()['retCode']
        if state == 0:
            # 获取认证信息
            url_L = 'https://rz.weijing.gov.cn/v2/api/concealhist'
            params_L = json.dumps({"accessToken": token, "authHistQry": {
                                  "certToken": condition['certToken']}})
            headers_L = {"Content-Type": "application/json; charset=UTF-8"}
            result_L = requests.post(
                url_L, data=params_L, headers=headers_L).json()
            # print(result_L)
            id_card_num = result_L['authData']['authObject']['idNum']
            status = result_L['retCode']
            # print(id_card_num)
            result = self.apply_old_age_allowance(
                {"id_card_num": id_card_num, "status": status})
            result = [result[0], {"id_card_num": id_card_num}]
            print(result)
            return result

    def apply_old_allowance(self, condition):
        '''高龄津贴申请'''
        res = 'Fail'

        # 判断是否申请过
        _filter = MongoBillFilter()
        _filter.match_bill((C('id_card') == condition['id_card']))\
            .project({'_id': 0})
        result = self.query(_filter, 'PT_Old_Allowance_Manage')
        if len(result) > 0:
            res = '已申请，不可重复申请'
        else:
            condition['create_time'] = datetime.datetime.now()
            condition['Status'] = '待受理'
            data_info = get_info(condition, self.session)
            bill_id = self.bill_manage_server.add_bill(
                OperationType.add.value, TypeId.allowance.value, data_info, 'PT_Old_Allowance_Manage')
            if bill_id:
                # 插入一个消息提醒
                self.MessageManageService.add_new_message({
                    # 高龄津贴标识
                    "business_type": 'old_age_allowance',
                    # 业务ID
                    "business_id": data_info['id']
                })
                res = '申请成功'
        return res

    def get_uncertified_person_list(self, condition, page, count):
        # 查询未认证的名单

        current_date = get_cur_time()
        if 'time' in condition.keys() and condition['time'] == '61-90':
            keys = ['id', 'name', 'id_card_num', 'town_street', 'village']
            values = self.get_value(condition, keys)
            _filter = MongoBillFilter()
            _filter.lookup_bill('PT_Old_Age_Allowance', 'id_card_num', 'id_card_num', 'rz_list')\
                .add_fields({
                    'new_date': self.ao.maximum('$rz_list.create_date')
                })\
                .add_fields({
                    'new_record': self.ao.array_filter('$rz_list', 'record', (F('$record.create_date') == '$new_date').f)
                })\
                .add_fields({'time_stamp': ((F('new_date')-current_date)*(-1)).f})\
                .add_fields({'days': self.ao.floor((F('time_stamp').__truediv__(86400000)).f)})\
                .match((C('id') == values['id'])
                       & (C('name').like(values['name']) | (C('id_card_num') == values['name']))
                       & (C('town_street').like(values['town_street']))
                       & (C('village').like(values['village']))
                       & (C('days') > 60)
                       & (C('days') <= 90))\
                .project({'_id': 0, 'rz_list._id': 0, 'new_record._id': 0})\
                .unwind('new_record')
        elif 'time' in condition.keys() and condition['time'] == '>90':
            keys = ['id', 'name', 'id_card_num', 'town_street', 'village']
            values = self.get_value(condition, keys)
            _filter = MongoBillFilter()
            _filter.lookup_bill('PT_Old_Age_Allowance', 'id_card_num', 'id_card_num', 'rz_list')\
                .add_fields({
                    'new_date': self.ao.maximum('$rz_list.create_date')
                })\
                .add_fields({
                    'new_record': self.ao.array_filter('$rz_list', 'record', (F('$record.create_date') == '$new_date').f)
                })\
                .add_fields({'time_stamp': ((F('new_date')-current_date)*(-1)).f})\
                .add_fields({'days': self.ao.floor((F('time_stamp').__truediv__(86400000)).f)})\
                .match((C('id') == values['id'])
                       & (C('name').like(values['name']) | (C('id_card_num') == values['name']))
                       & (C('town_street').like(values['town_street']))
                       & (C('village').like(values['village']))
                       & (C('days') > 90))\
                .project({'_id': 0, 'rz_list._id': 0, 'new_record._id': 0})
        else:
            keys = ['id', 'name', 'id_card_num', 'town_street', 'village']
            values = self.get_value(condition, keys)
            _filter = MongoBillFilter()
            _filter.lookup_bill('PT_Old_Age_Allowance', 'id_card_num', 'id_card_num', 'rz_list')\
                .add_fields({
                    'new_date': self.ao.maximum('$rz_list.create_date')
                })\
                .add_fields({
                    'new_record': self.ao.array_filter('$rz_list', 'record', (F('$record.create_date') == '$new_date').f)
                })\
                .add_fields({'time_stamp': ((F('new_date')-current_date)*(-1)).f})\
                .add_fields({'days': self.ao.floor((F('time_stamp').__truediv__(86400000)).f)})\
                .match((C('id') == values['id'])
                       & (C('name').like(values['name']) | (C('id_card_num') == values['name']))
                       & (C('town_street').like(values['town_street']))
                       & (C('village').like(values['village']))
                       & (C('days') > 60))\
                .project({'_id': 0, 'rz_list._id': 0, 'new_record._id': 0})
        res_list = self.page_query(_filter, 'PT_Old_Age_List', page, count)
        return res_list
